# 导包
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import unittest
from tools.tools import Tools
from ddt import ddt, data
from page_model import login
from tools.read_excel import ReadTestData


# 写测试用例类
@ddt
class MmsLoginTest(unittest.TestCase):
    # 登录正向用例的测试数据
    x = ReadTestData('./test_data/mms_test_data.xls')
    users_t = x.read_excel('login_t')
    users_f = x.read_excel('login_f')

    def setUp(self) -> None:
        # 创建浏览器对象
        self.dr = webdriver.Chrome()
        self.dr.implicitly_wait(5)
        self.dr.maximize_window()
        self.login = login.Login(self.dr)

    def tearDown(self) -> None:
        time.sleep(3)
        self.dr.quit()

    # 登录的正向用例
    @data(*users_t)
    def testLoginT(self, user):
        self.login.login(user)
        try:  # 如果没有正确打开登录页在此定位用户名标签会出错
            # 断言-是否打开了指定的网页
            ex_url = 'http://localhost:8080/mms/mms/index.html'
            self.assertEqual(ex_url, self.dr.current_url, '登录未打开正确页面')
            # 断言-是否显示当前登录用户名
            ex_name = user['name']
            name_text = self.dr.find_element(By.ID, 'loginName').text
            self.assertEqual(ex_name, name_text, '标签未找到或没有显示登录用户名')
        except Exception as e:
            # 截图并保存
            Tools.save_screenshot(self.dr, 'login_t')
            raise e

    # 登录的反向用例
    @data(*users_f)
    def testLoginF(self, user):
        # 调用登录页面对象的登陆方法
        self.login.login(user)
        # 断言 定位错误提示标签获取显示文本与预期结果对比
        try:
            text = self.dr.find_element(By.XPATH,
                                        '//div[@class="messager-body panel-body panel-body-noborder window-body"]/div').text
            self.assertEqual(user['expect_text'], text, '错误')
        except Exception as f:
            Tools.save_screenshot(self.dr, 'login_f')
            raise f
